package com.jzo2o.orders.manager.strategy.impl;

import com.jzo2o.orders.base.enums.OrderRefundStatusEnum;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.mapper.OrdersCanceledMapper;
import com.jzo2o.orders.base.mapper.OrdersRefundMapper;
import com.jzo2o.orders.base.model.domain.OrdersCanceled;
import com.jzo2o.orders.base.model.domain.OrdersRefund;
import com.jzo2o.orders.base.model.dto.OrderUpdateStatusDTO;
import com.jzo2o.orders.base.service.IOrdersCommonService;
import com.jzo2o.orders.manager.model.dto.OrderCancelDTO;
import com.jzo2o.orders.manager.strategy.OrderCancelStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 普通用户取消派单中的订单策略
 */
@Component("1:DISPATCHING")
public class CommonUserDispatchingOrderCancelStrategy implements OrderCancelStrategy {
    @Autowired
    private IOrdersCommonService ordersCommonService;
    @Autowired
    private OrdersCanceledMapper ordersCanceledMapper;
    @Autowired
    private OrdersRefundMapper ordersRefundMapper;
    @Override
    public void cancel(OrderCancelDTO orderCancelDTO) {
        //修改订单状态为已关闭
        OrderUpdateStatusDTO dto = OrderUpdateStatusDTO.builder()
                //订单id
                .id(orderCancelDTO.getId())
                //原始状态
                .originStatus(OrderStatusEnum.DISPATCHING.getStatus())
                //目标状态
                .targetStatus(OrderStatusEnum.CLOSED.getStatus())
                //退款状态
                .refundStatus(OrderRefundStatusEnum.REFUNDING.getStatus())
                .build();
        Integer i = ordersCommonService.updateStatus(dto);
        if (i<=0){
            throw new RuntimeException("订单取消失败");
        }
        //保存取消订单的记录
        OrdersCanceled ordersCanceled = new OrdersCanceled();
        //订单id
        ordersCanceled.setId(orderCancelDTO.getId());
        //取消人id
        ordersCanceled.setCancellerId(orderCancelDTO.getCurrentUserId());
        //取消人名称
        ordersCanceled.setCancelerName(orderCancelDTO.getCurrentUserName());
        //取消人类型
        ordersCanceled.setCancellerType(orderCancelDTO.getCurrentUserType());
        //取消原因
        ordersCanceled.setCancelReason(orderCancelDTO.getCancelReason());
        //取消时间
        ordersCanceled.setCancelTime(LocalDateTime.now());
        //插入订单取消表
        ordersCanceledMapper.insert(ordersCanceled);

        //添加待退款记录
        OrdersRefund ordersRefund = new OrdersRefund();
        //订单id
        ordersRefund.setId(orderCancelDTO.getId());
        //支付服务交易单号
        ordersRefund.setTradingOrderNo(orderCancelDTO.getTradingOrderNo());
        //实付金额
        ordersRefund.setRealPayAmount(orderCancelDTO.getRealPayAmount());

        ordersRefund.setCreateTime(LocalDateTime.now());
        //插入订单退款表
        ordersRefundMapper.insert(ordersRefund);
    }
}
